package com.dave.start;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.*;
import java.util.stream.Collectors;

/**
 * @Author Dave
 * @Date 2018/8/9
 * @Description
 */
public class AppleChooser {


    ///////////////////////////////////////////////////////////////////////////
    // 由于predicate、consumer、function都是应用类型的，在自动装箱时会损耗性能
    // 针对专门的输入参数类型的函数式接口的名称都要加上对应的原始类型前缀，
    // 比 如DoublePredicate、IntConsumer、LongBinaryOperator、IntFunction
    ///////////////////////////////////////////////////////////////////////////

    /**
     * 苹果筛选 predicate
     *
     * @param predicate
     * @param apples
     * @return
     */
    private List<Apple> chooseApple(Predicate<Apple> predicate, List<Apple> apples) {
        List<Apple> list = new ArrayList<>();
        for (Apple apple : apples) {
            if (predicate.test(apple)) {
                list.add(apple);
            }
        }
        return list;

    }

    /**
     * 打印苹果 consumer
     *
     * @param consumer
     * @param apples
     * @return
     */
    private void forEach(Consumer<Apple> consumer, List<Apple> apples) {
        for (Apple apple : apples) {
            consumer.accept(apple);
        }
    }

    /**
     * 得到苹果的重量 function
     *
     * @param function
     * @param apples
     * @return
     */
    private List<Integer> getEachWeight(Function<Apple, Integer> function, List<Apple> apples) {
        List<Integer> weightList = new ArrayList<>();
        for (Apple apple : apples) {
            Integer weight = function.apply(apple);
            weightList.add(weight);
        }
        return weightList;

    }

    public static void main(String[] args) {
        List<Apple> apples = Arrays.asList(
                new Apple(150, Apple.COLOR_GREEN),
                new Apple(100, Apple.COLOR_RED),
                new Apple(200, Apple.COLOR_RED)
        );
        List<Apple> result = new AppleChooser().chooseApple(e -> e.getWeight() > 100, apples);
        for (Apple apple : result) {
            System.out.println(apple);
        }

        //流式筛选 行为参数化
        result = apples.stream()
                .filter(e -> e.getColor().equals(Apple.COLOR_GREEN))
                .collect(Collectors.toList());

        //遍历
        new AppleChooser().forEach(e -> {
            System.out.printf("color:%S,weight:%s\n", e.getColor(), e.getColor());
        }, apples);

        //映射另一个类型
        new AppleChooser().getEachWeight(Apple::getWeight, apples);
        


    }


}
